import { login, logout, register, getInfo } from '@/api/user'
import { getOrganizaiton } from '@/api/organization'
import { getSession, setSession, removeSession } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import store from '../index'

const state = {
  session: getSession(),
  userInfo: null,
  roles: []
}

const mutations = {
  SET_SESSION: (state, session) => {
    state.session = session
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
    sessionStorage.setItem('store', JSON.stringify(store.state))
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise(async(resolve, reject) => {
      await login({ username: username.trim(), password: password }).then(async response => {
        const { data } = response
        commit('SET_SESSION', getSession())

        switch (data.user_type) {
          case 1:
            commit('SET_ROLES', ['super', 'admin'])
            break
          case 2:
            commit('SET_ROLES', ['admin'])
            break
          default:
            commit('SET_ROLES', ['editor'])
            break
        }
        commit('SET_USERINFO', data)

        resetRouter()
        const accessRoutes = await store.dispatch('permission/generateRoutes', state.roles)
        router.$addRoutes(accessRoutes)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user register
  register({ commit }, userInfo, type = 3) {
    const { username, code, password, password_confirm } = userInfo
    return new Promise((resolve, reject) => {
      register({ username: username.trim(), nickname: username.trim(), code: code, user_type: type, password: password, password_confirm: password_confirm }).then(response => {
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.session).then(response => {
        const { data } = response
        commit('SET_SESSION', getSession())

        switch (data.user_type) {
          case 1:
            commit('SET_ROLES', ['super', 'admin'])
            break
          case 2:
            commit('SET_ROLES', ['admin'])
            break
          default:
            commit('SET_ROLES', ['editor'])
            break
        }
        commit('SET_USERINFO', data)
        resolve(Object.assign(data, { roles: state.roles }))
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get rganizaiton by user_id
  getOrganizaiton({ commit }, user_id) {
    return new Promise((resolve, reject) => {
      getOrganizaiton({ 'user_id': user_id }).then(res => {
        const { data } = res
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logoutWithSession({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.session).then(() => {
        commit('SET_SESSION', '')
        commit('SET_USERINFO', null)
        commit('SET_ROLES', [])
        sessionStorage.clear()
        removeSession()
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      try {
        commit('SET_SESSION', '')
        commit('SET_USERINFO', null)
        commit('SET_ROLES', [])
        sessionStorage.clear()
        removeSession()
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })
        resolve()
      } catch (error) {
        reject(error)
      }
    })
  },

  // remove session
  resetSession({ commit }) {
    return new Promise(resolve => {
      commit('SET_SESSION', '')
      commit('SET_ROLES', [])
      removeSession()
      resolve()
    })
  },

  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const session = role + '-session'

      commit('SET_SESSION', session)
      setSession(session)

      const { roles } = await dispatch('getInfo')

      resetRouter()

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
    })
  },

  // chagne current department
  changeCurDepartment({ commit }, department) {
    commit('SET_CUR_DEPARTMENT', department)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
